
import java.awt.Image;
import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

/**
 *
 * @author Administrador
 */
public class VentanaPrincipal extends JFrame implements ListSelectionListener{
    private Modelo modelo;
    private String season;
    private String chapter;
    private ImageIcon image;
    private String[] series;
    private String selectedSerie;

    /**
     * Constructor sin serie seleccionada, se pedirá un directorio de una serie
     * @param modelo Modelo "controlador" con el que se comunica
     */
    public VentanaPrincipal(Modelo modelo, boolean hayDirectorio) {
        this.modelo = modelo;
        this.season = "";
        this.chapter = "";
        this.selectedSerie = "";
        this.series= new String[0];
        
        initComponents();
        initComponents2();
        
        if(!hayDirectorio){
            pedirDirectorio();
            updateList();
        }
    }
    
    /**
     * Constructor en el que hace una serie seleccionada
     * @param modelo Modelo "controlador" con el que se comunica
     * @param series Listado de series del directorio
     * @param image Imagen de la serie
     * @param season Nombre de la temporada
     * @param chapter Nombre del capítulo
     */
    public VentanaPrincipal(Modelo modelo, String[] series, ImageIcon image, String season, String chapter, String selectedSerie) {
        this.modelo = modelo;
        this.season = season;
        this.chapter = chapter;
        this.image = image;
        this.selectedSerie = selectedSerie;
        this.series = series;
        this.image = image;
        
        initComponents();
        initComponents2();
        
        if(series.length == 0 || series == null){
            pedirDirectorio();
            updateList();
        }else{
            updateList();
            jlSeries.setSelectedValue(selectedSerie, true);
            updateImage();
        }
        this.setVisible(true);
    }
    
    public void setAll(String[] series, ImageIcon image, String season, String chapter, String selectedSerie){
        this.setBackgroundImage(image);
        this.setSeason(season);
        this.setChapter(chapter);
        this.setSeries(series);
        this.setSelectedSerie(selectedSerie);
    }
    
    public void setSeries(String[] series){
        this.series = series;
        updateList();
    }
    
    public void setSelectedSerie(String selectedSerie){
        this.selectedSerie = selectedSerie;
        jlSeries.setSelectedValue(selectedSerie, true);
    }
    
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jbPlay = new javax.swing.JButton();
        jbLastChapter = new javax.swing.JButton();
        jbLastSeason = new javax.swing.JButton();
        jbNextChapter = new javax.swing.JButton();
        jbNextSeason = new javax.swing.JButton();
        jlImagenFondo = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jlSeries = new javax.swing.JList();
        jbBrowse = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jbPlay.setToolTipText("Reproducir capítulo");
        jbPlay.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbPlayActionPerformed(evt);
            }
        });
        getContentPane().add(jbPlay, new org.netbeans.lib.awtextra.AbsoluteConstraints(410, 310, 70, 60));

        jbLastChapter.setToolTipText("Capítulo anterior");
        jbLastChapter.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbLastChapterActionPerformed(evt);
            }
        });
        getContentPane().add(jbLastChapter, new org.netbeans.lib.awtextra.AbsoluteConstraints(300, 330, 40, 40));

        jbLastSeason.setToolTipText("Temporada anterior");
        jbLastSeason.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbLastSeasonActionPerformed(evt);
            }
        });
        getContentPane().add(jbLastSeason, new org.netbeans.lib.awtextra.AbsoluteConstraints(200, 330, 40, 40));

        jbNextChapter.setToolTipText("Capítulo siguiente");
        jbNextChapter.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbNextChapterActionPerformed(evt);
            }
        });
        getContentPane().add(jbNextChapter, new org.netbeans.lib.awtextra.AbsoluteConstraints(560, 330, 40, 40));

        jbNextSeason.setToolTipText("Temporada siguiente");
        jbNextSeason.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbNextSeasonActionPerformed(evt);
            }
        });
        getContentPane().add(jbNextSeason, new org.netbeans.lib.awtextra.AbsoluteConstraints(660, 330, 40, 40));
        getContentPane().add(jlImagenFondo, new org.netbeans.lib.awtextra.AbsoluteConstraints(180, 0, 540, 380));

        jScrollPane1.setViewportView(jlSeries);

        getContentPane().add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 180, 340));

        jbBrowse.setText("Cambiar directorio...");
        jbBrowse.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbBrowseActionPerformed(evt);
            }
        });
        getContentPane().add(jbBrowse, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 340, 180, 40));

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jbBrowseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbBrowseActionPerformed
        pedirDirectorio();
        updateList();
    }//GEN-LAST:event_jbBrowseActionPerformed

    private void jbPlayActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbPlayActionPerformed
        modelo.reproducir();
    }//GEN-LAST:event_jbPlayActionPerformed

    private void jbNextChapterActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbNextChapterActionPerformed
        modelo.nextChapter();
        if(modelo.isLastChapter()){
            jbNextChapter.setEnabled(false);
        }
        jbLastChapter.setEnabled(true);
    }//GEN-LAST:event_jbNextChapterActionPerformed

    private void jbNextSeasonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbNextSeasonActionPerformed
        modelo.nextSeason();
    }//GEN-LAST:event_jbNextSeasonActionPerformed

    private void jbLastChapterActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbLastChapterActionPerformed
        modelo.previousChapter();
    }//GEN-LAST:event_jbLastChapterActionPerformed

    private void jbLastSeasonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbLastSeasonActionPerformed
        modelo.previousSeason();
    }//GEN-LAST:event_jbLastSeasonActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JButton jbBrowse;
    private javax.swing.JButton jbLastChapter;
    private javax.swing.JButton jbLastSeason;
    private javax.swing.JButton jbNextChapter;
    private javax.swing.JButton jbNextSeason;
    private javax.swing.JButton jbPlay;
    private javax.swing.JLabel jlImagenFondo;
    private javax.swing.JList jlSeries;
    // End of variables declaration//GEN-END:variables

    private void initComponents2() {
        this.setLocationRelativeTo(null);
        ImageIcon icono = new ImageIcon(getClass().getResource("/imagenes/interior1.png"));
        Image imagen = icono.getImage();
        ImageIcon iconoEscalado = new ImageIcon(imagen.getScaledInstance(this.getWidth(),this.getHeight(), Image.SCALE_SMOOTH));
        jlImagenFondo.setIcon(iconoEscalado);
        
        jlSeries.addListSelectionListener(this);
        
        this.setTitle(season + " - " + chapter);
    }
    
    /**
     * Cambia la imagen de fondo de la serie
     * @param image Imagen a mostrar de fondo
     */
    public void setBackgroundImage(ImageIcon image){
        this.image = image;
        updateImage();
    }
    
    /**
     * Cambia el texto de la interfaz que muestra el nombre del capítulo
     * @param chapter El nombre del capítulo
     */
    public void setChapter(String chapter){
        this.chapter = chapter;
        updateTitle();
    }
    
    /**
     * Cambia el texto de la interfaz que muestra el nombre de la temporada
     * @param season El nombre de la temporada
     */
    public void setSeason(String season){
        this.season = season;
        updateTitle();
    }

    private String pedirDirectorioSeries() {
        String directorio = null;
        
        JFileChooser chooser = new JFileChooser();
        chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        chooser.setAcceptAllFileFilterUsed(false);
        int returnVal = chooser.showOpenDialog(this);
        if(returnVal == JFileChooser.APPROVE_OPTION) {
            directorio = chooser.getSelectedFile().getAbsolutePath();
        }
        
        return directorio;
    }

    private void updateTitle() {
        this.setTitle(season + " - " + chapter);
    }
    
    private void updateImage() {
        if(image.getIconWidth() != -1){ //Comprueba si no existe la imagen (pero no es null)
            Image img = this.image.getImage();
            ImageIcon iconoEscalado = new ImageIcon(img.getScaledInstance(jlImagenFondo.getWidth(),jlImagenFondo.getHeight(), Image.SCALE_SMOOTH));
            jlImagenFondo.setIcon(iconoEscalado);
            repaint();
        }
    }

    @Override
    public void valueChanged(ListSelectionEvent lse) {
        JList jl = (JList)lse.getSource();
        if(jl.isSelectionEmpty()){
            setSelectedSerie(series[0]);
        }
        String value = jl.getSelectedValue().toString();
        if(!value.equals(selectedSerie)){
            modelo.setSerie(value);
            selectedSerie = value;
        }
        
    }

    private void updateList() {
        if(series.length==0){
            pedirDirectorio();
        }
        
        DefaultListModel dl = new DefaultListModel();
       
        for(int i=0; i < series.length; i++){
            dl.addElement(series[i]);
        }
        
        jlSeries.setModel(dl);
    }

    private void pedirDirectorio() {
        String path;
        do{
            path = pedirDirectorioSeries();
            if(path == null){
                System.exit(0);
            }

            series = modelo.getSeries(path);

        } while (series.length == 0);
        
    }
}
